using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace QNLua.CommonData
{
    public class IntOrStringConverter : JsonConverter<string>
    {
        public override string ReadJson(JsonReader reader, Type objectType, string existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            var token = JToken.Load(reader);

            // 不管是 int 还是 string，都转为 string
            return token.ToString();
        }

        public override void WriteJson(JsonWriter writer, string value, JsonSerializer serializer)
        {
            writer.WriteValue(value);
        }
    }

    public class NumberOrStringArrayConverter : JsonConverter<List<string>>
    {
        public override List<string> ReadJson(JsonReader reader, Type objectType, List<string> existingValue, bool hasExistingValue, JsonSerializer serializer)
        {
            var token = JToken.Load(reader);
            var result = new List<string>();

            // 如果是数组
            if (token.Type == JTokenType.Array)
            {
                foreach (var item in token)
                {
                    // 将每个元素转换为 string
                    result.Add(item.ToString());
                }
            }

            return result;
        }

        public override void WriteJson(JsonWriter writer, List<string> value, JsonSerializer serializer)
        {
            writer.WriteStartArray();
            foreach (var item in value)
            {
                writer.WriteValue(item);
            }
            writer.WriteEndArray();
        }
    }
}